package com.hankol.newretail

import android.graphics.Color
import android.os.Build
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.MessageBus
import com.baselibrary.adapter.StateViewPagerAdapter
import com.baselibrary.adapter.ViewPagerAdapter
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.EventBusUtils
import com.baselibrary.utils.GlideUtils
import com.baselibrary.utils.ScreenUtils
import com.baselibrary.utils.StatusBarUtil
import com.google.android.material.appbar.AppBarLayout
import com.baselibrary.activity.BaseActivity
import com.hankol.newretail.databinding.ActivitySeckillBinding
import com.hankol.newretail.fragment.SeckillFragment
import com.hankol.newretail.viewmodel.SeckillViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 *@author:hanke
 *2022/9/5
 *desc:
 */
@Route(path = ActivityRouter.NEW_RETAIL.SECKILL)
class SeckillActivity : BaseActivity(), View.OnClickListener, AppBarLayout.OnOffsetChangedListener {
    private lateinit var dataBinding: ActivitySeckillBinding
    private lateinit var viewModel: SeckillViewModel
    private var selectedPosition = 0;
    private var height = 0;
    override fun getLayoutId(): Int {
        initImmersion(true)
        return R.layout.activity_seckill
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        dataBinding = getDataBinding<ActivitySeckillBinding>()
        viewModel = getActivityViewModelProvider(this).get(SeckillViewModel::class.java)
        initView()
        initListener()
        initObserver()
        requestData()
        SensorsDataManager.instance.onCreateTime()
    }

    private fun initListener() {
        dataBinding.ivBack.setOnClickListener(this)

    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun initObserver() {
        viewModel.seckillConfigLD.observe(this, Observer {
            viewModel.reqSeckillCategory()
            if (it != null) {
                if (it.categoryBanner.checkNotNull()) {
                    dataBinding.bannerSeckill.visibility = View.VISIBLE
                    GlideUtils.loadImg_228(SeckillActivity@ this, it.categoryBanner, dataBinding.bannerSeckill)
                    height = ((ScreenUtils.getScreenWidth() * 237).toFloat() / 375).toInt()
                    val p: ViewGroup.LayoutParams = dataBinding.bannerSeckill.layoutParams
                    p.height = height
                    dataBinding.bannerSeckill.layoutParams = p
                    dataBinding.ablTop.addOnOffsetChangedListener(this)
                } else {
                    dataBinding.ablTop.removeOnOffsetChangedListener(this)
                    dataBinding.bannerSeckill.visibility = View.GONE
                    dataBinding.toolbar.alpha = 1F
                }
            }
        })

        viewModel.seckillCategoryLD.observe(this, Observer {
            dataBinding.llLoading.visibility = View.GONE
            if (it.isNotEmpty()) {
                val titles = java.util.ArrayList<String>()
                val fragments = java.util.ArrayList<Fragment>()
                val defaultIcons = ArrayList<String>()
                val selectedIcons = ArrayList<String>()
                for (data in it) {
                    titles.add(data.name)
                    fragments.add(SeckillFragment.newInstance(data.showType, data.id))
                    if (data.imgPower == 1) {
                        defaultIcons.add(data.defaultImg)
                        selectedIcons.add(data.selectedImg)
                    } else {
                        defaultIcons.add("")
                        selectedIcons.add("")
                    }
                }
                dataBinding.vpSeckil.adapter = StateViewPagerAdapter(supportFragmentManager, fragments)
                dataBinding.vpSeckil.offscreenPageLimit = fragments.size
                dataBinding.istSeckill.setViewPager(dataBinding.vpSeckil, titles.toTypedArray())
                dataBinding.istSeckill.setSelectedIcons(selectedIcons)
                dataBinding.istSeckill.setUnselectedIcons(defaultIcons)
                dataBinding.istSeckill.setShowIndicator(true)
                dataBinding.istSeckill.setIsRed(true)
                dataBinding.vpSeckil.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                    }

                    override fun onPageSelected(position: Int) {
                        selectedPosition = position
                        if (titles.size > 0) {
                            SensorsDataManager.instance.seckillClassifyClick(titles[position].checkValue())
                        }
                    }

                    override fun onPageScrollStateChanged(state: Int) {
                    }
                })
                dataBinding.vpSeckil.currentItem = selectedPosition
                dataBinding.istSeckill.updateTabSelection(selectedPosition)
            }
        })
    }

    private fun setWhiteMode() {
        dataBinding.tvTitle.setTextColor(ContextCompat.getColor(this, R.color.black))
        dataBinding.toolbar.setBackgroundColor(Color.argb(255, 255, 255, 255))
        dataBinding.ivBack.setImageResource(R.drawable.ic_base_back)
        dataBinding.tvTitle.setTextColor(Color.argb(255, 0, 0, 0))
        StatusBarUtil.setStatusBarDarkTheme(this, true)
    }

    private fun requestData() {
        viewModel.reqSeckillConfig()
    }

    private fun initView() {
        dataBinding.llLoading.visibility = View.VISIBLE
        dataBinding.smartRefresh.setEnableLoadMore(false)
        dataBinding.smartRefresh.setOnRefreshListener {
            viewModel.reqSeckillConfig()
            EventBusUtils.sendNotify(MessageBus.msgId_refresh_seckill)
        }
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_refresh_seckill_complete) {
            dataBinding.smartRefresh.finishRefresh()
        }
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back, R.id.iv_back_white -> {
                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        SensorsDataManager.instance.onDestroyTime()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        try {
            if (SensorsDataManager.instance.getBrowseTime() != 0L) {
                SensorsDataManager.instance.seckillPageView()
            }
        } catch (e: Exception) {

        }
    }

    override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
        val offset = height - ScreenUtils.dpToPx(84)
        val scale = (-verticalOffset).toFloat() / offset
        dataBinding.toolbar.alpha = scale
    }
}